package com.hbd.esdemo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.hbd.esdemo.pojo.ShipAddress;
import com.hbd.esdemo.repository.ShipAddressRepository;
import com.hbd.esdemo.service.IShipAddressService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

/**
 * 收货地址
 *
 * @author bdhong
 */

@Service
public class ShipAddressServiceImpl implements IShipAddressService {

    @Autowired
    private ShipAddressRepository shipAddressRepository;

    @Override
    public Iterable<ShipAddress> list(String address) {

        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();

        if (StrUtil.isNotEmpty(address)) {
            // 词条查询
            queryBuilder = QueryBuilders.multiMatchQuery(address, "province", "city", "area", "street");
        }
        return this.shipAddressRepository.search(queryBuilder);
    }

    @Override
    public Page<ShipAddress> page(String address, int page, int size) {

//        int i = 1/0;

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        if (StrUtil.isNotEmpty(address)) {

            // 添加分词查询
            queryBuilder.withQuery(QueryBuilders.multiMatchQuery(address, "province", "city", "area", "street"));

        }
        // 设置分页参数
        queryBuilder.withPageable(PageRequest.of(page - 1, size));

        return this.shipAddressRepository.search(queryBuilder.build());
    }
}
